package com.jack.screenprojectionpushsimple

import android.Manifest
import android.R.id.message
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.os.RemoteException
import android.util.DisplayMetrics
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlin.properties.Delegates


class MainActivity : AppCompatActivity() {
    private lateinit var mMediaProjectionManager: MediaProjectionManager
    private lateinit var mSocketClient: SocketClient
    private lateinit var mDisplayMetrics: DisplayMetrics
    private lateinit var mMediaService: MediaService
    private lateinit var mIntent: Intent
    private var mScreenWidth by Delegates.notNull<Int>()
    private var mScreenHeight by Delegates.notNull<Int>()

    private val CONST_REQUEST_CODE = 0x001

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        checkPermission(this)
        mDisplayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(mDisplayMetrics)
        mScreenWidth = mDisplayMetrics.widthPixels
        mScreenHeight = mDisplayMetrics.heightPixels

        mIntent = Intent(this, MediaService::class.java)
        bindService(mIntent, conn, BIND_AUTO_CREATE)

//        initBroadcast()

        beginScreenProjection()
    }

//    private val mBroadcastReceiver = object : BroadcastReceiver() {
//        override fun onReceive(context: Context?, intent: Intent?) {
//            TODO("Not yet implemented")
//        }
//
//    }

//    private fun initBroadcast() {
//        val intentFilter = IntentFilter()
//        intentFilter.addAction("cn.jack.projection")
//        registerReceiver(mBroadcastReceiver, intentFilter)
//    }

    private var mMessenger: Messenger = Messenger(object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            if (msg.what == 23) {
                val mediaProjection: MediaProjection = msg.obj as MediaProjection
                mSocketClient.start(mediaProjection)
            }
        }
    })

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode === CONST_REQUEST_CODE && resultCode === RESULT_OK) {
            mSocketClient = SocketClient(9999, mScreenWidth, mScreenHeight)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //将mediaProjectionManager传进service里，这个manager你应该已经在`ServiceConnection`时实例化好了（）
                mMediaService.setMediaProjectionManager(mMediaProjectionManager)
                mIntent.putExtra("code", resultCode)
                mIntent.putExtra("data", data)
                mIntent.putExtra("messenger", mMessenger)
                startForegroundService(mIntent)
            } else {
                data?.let {
                    //1.获取到录屏的类
                    val mediaProjection =
                        mMediaProjectionManager.getMediaProjection(resultCode, data)
                    mSocketClient.start(mediaProjection)
                }
            }
        }
    }

    private var conn: ServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName) {}
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            mMediaService = (service as MediaService.MsgBinder).service
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mSocketClient.close()
        unbindService(conn)
        stopService(mIntent)
//        unregisterReceiver(mBroadcastReceiver)
    }

    fun checkPermission(activity: Activity): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) !== PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                activity,
                arrayOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                1
            )
        }
        return false
    }

    fun beginScreenProjection() {
        mMediaProjectionManager =
            getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        val captureIntent: Intent = mMediaProjectionManager.createScreenCaptureIntent()
        startActivityForResult(captureIntent, CONST_REQUEST_CODE)
    }
}